package com.homework.ch02;

import java.util.Optional;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/23
 * @Description:
 */
public class Test05 {
    public static void main(String[] args) {
        //of ofNullable()方法可以将null值转换为Optional对象
        Optional<String> op1=Optional.of("hello");
        //Optional<Object> op12 = Optional.of(null); of不能使用null
        Optional<String> op2=Optional.ofNullable(null);//可以包含null值
        //判断Optional对象是否包含值，isPresent()方法
        if(op2.isPresent()){
            System.out.println("op2 is present and value is ");
        }else{
            System.out.println("op2 is not present");
        }
        //简化版的ifPresent()方法
        op2.ifPresent(s->System.out.println(op2.get()));
        op1.ifPresent(System.out::println);
        //返回默认值或其他值，orElse()和orElseGet()方法
        //orElse()方法返回当前Optional对象的值，如果当前对象为空，则返回默认值
        System.out.println(op1.orElse("default value"));
        System.out.println(op2.orElse("Other"));
        //orElseGet()方法返回一个Supplier接口的实现类的get方法的返回值，如果当前对象为空，则返回Supplier接口的实现类的get方法的返回值
        System.out.println(op1.orElseGet(() -> "default value"));
        System.out.println(op2.orElseGet(() -> "Other"));
        //mao方法
        Optional<Integer> i=op1.map(str->str.length());
        System.out.println(i.get());
        System.out.println(i);
        Optional<Integer> i2=op2.map(str->str.length());
        System.out.println(i2);
        Optional<Integer> j=op1.flatMap(str->Optional.of(2));
        System.out.println(j);
        Optional<Integer> j1=op2.flatMap(str->Optional.ofNullable(null));
        System.out.println(j1);
    }
}
